package com.fenghongzhang.day003;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 三级缓存,来操作图片
 */
public class ImagerLoader {
    private static final String TAG = "ImagerLoader";

    private static ImagerLoader imagerLoader;

//    private Map<String, Bitmap> map;
    private LruCache<String,Bitmap> lruCache; //put  get
    //线程池
    private ExecutorService executorService;
    private ImagerLoader(){
        executorService = Executors.newSingleThreadExecutor();
        //取到当前手机内存
        int l = (int) (Runtime.getRuntime().maxMemory() / 10);
        //初始化
        lruCache = new LruCache<String, Bitmap>(l){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount(); //图片的大小
            }
        };
    }

    public static ImagerLoader getInstance(){
        if (imagerLoader == null){
            synchronized (ImagerLoader.class){
                if(imagerLoader == null){
                    imagerLoader = new ImagerLoader();
                }
            }
        }
        return imagerLoader;
    }


    //读取图片
    public void loading(final String url){
        //1,从内存里面 读.如果没有就从sd中 读,如果 还没有,就从网络上读
//        http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg
        //怎么取到值.字符串截取
        final String substring = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
//        lruCache.put("",)
        //1,从内存中取
        final Bitmap bitmap = lruCache.get(substring);
        if(bitmap != null){
            //给imageview
            Log.i(TAG, "loading: 从内存中读");
            myListener.load(bitmap);
        }else{
            //2,从sd卡 ,根据文件名称来读

            Bitmap bitmap1 = readFromSd(substring);
            if(bitmap1 != null){
                Log.i(TAG, "loading: 从sd读取 ");
                myListener.load(bitmap1);
                lruCache.put(substring,bitmap1);
            }else{
                //3, 从网络上来.
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                    }
//                }).start();

                //子线程和主线程交互
                final Handler handler = new Handler(){
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);

                        Bitmap bitmap2 = (Bitmap) msg.obj;
                        myListener.load(bitmap2);
                    }
                };

                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        //下载
                        try {
                            Log.i(TAG, "run: 从网络下载.");
                            URL u = new URL(url);
                            HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection();
                            if(urlConnection.getResponseCode() == 200){
                                InputStream inputStream = urlConnection.getInputStream();
                                Bitmap bitmap2 = BitmapFactory.decodeStream(inputStream);

//                                myListener.load(bitmap2);

                                //添加到sd卡
                                savaToSD(substring,bitmap2);
                                //添加到内存
                                lruCache.put(substring,bitmap2);

                                //发走
                                Message obtain = Message.obtain();
                                obtain.obj  = bitmap2;
                                handler.sendMessage(obtain);

                            }

                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                });

            }
        }

    }


    private void savaToSD(String name,Bitmap bitmap) {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //写 /storage/emulated/0/image
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image");
            if(!file.exists()){
                file.mkdirs();
            }
            Log.i(TAG, "savaToSD: 存的路径"+file.getAbsolutePath());
            FileOutputStream fileOutputStream = null;
            try {
                 fileOutputStream = new FileOutputStream(new File(file, name));
                 bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else{
            Log.i(TAG, "savaToSD: 没有sd卡");
        }
    }

    //根据文件名称来读
    private Bitmap readFromSd(String name) {
        //sd/dat/829.jpg
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image" + File.separator);
        return   BitmapFactory.decodeFile(new File(file,name).getAbsolutePath());
    }



    public interface MyListener{
        void load(Bitmap bitmap);
    }
    private MyListener myListener;

    public void setMyListener(MyListener myListener) {
        this.myListener = myListener;
    }
}
